# import socket
# s=socket.socket()
# host=socket.gethostname()
# port=12345
# s.connect((host,port))  #连接服务，指定主机和端口
# print(s.recv(1024).decode('utf-8'))  #接收服务端信息
# s.close()


import socket
import tkinter as tk
from threading import Thread

# 创建主窗口
root = tk.Tk()
root.title("Socket 客户端")
root.geometry("600x400")

# 全局变量
client_socket = None
connected = False

# 连接服务器
def connect_server():
    global client_socket, connected
    if connected:
        return
    
    host = host_entry.get()
    port = int(port_entry.get())
    
    try:
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((host, port))
        connected = True
        status_label.config(text=f"已连接到服务器 {host}:{port}")
        
        # 在消息显示区域也显示连接成功的消息
        message_text.insert(tk.END, f"✅ 成功连接到服务器 {host}:{port}\n")
        message_text.see(tk.END)  # 自动滚动到底部
        
        # 启动接收消息的线程
        Thread(target=receive_messages, daemon=True).start()
    except Exception as e:
        status_label.config(text=f"连接失败: {e}")
        message_text.insert(tk.END, f"❌ 连接失败: {e}\n")  # 可选：也在消息区显示错误
        message_text.see(tk.END)

# 接收来自服务器的消息
def receive_messages():
    global client_socket
    while connected:
        try:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                break
            message_text.insert(tk.END, f"收到消息: {data}\n")
            message_text.see(tk.END)
        except Exception as e:
            status_label.config(f"接收错误: {e}")
            break

# 发送消息给服务器
def send_message():
    global client_socket
    msg = message_entry.get()
    if msg and client_socket:
        try:
            client_socket.send(msg.encode('utf-8'))
            message_text.insert(tk.END, f"发送消息: {msg}\n")
            message_text.see(tk.END)
            message_entry.delete(0, tk.END)
        except Exception as e:
            status_label.config(text=f"发送失败: {e}")

# 断开连接
def disconnect():
    global client_socket, connected
    if not connected:
        return
    connected = False
    if client_socket:
        client_socket.close()
        client_socket = None
    status_label.config(text="已断开连接")
    message_text.insert(tk.END, "🔌 已断开与服务器的连接。\n")
    message_text.see(tk.END)

# GUI 布局

# 服务器地址输入
tk.Label(root, text="服务器地址：").grid(row=0, column=0, padx=10, pady=10)
host_entry = tk.Entry(root)
host_entry.grid(row=0, column=1, padx=10, pady=10)
host_entry.insert(0, "localhost")  # 默认连接本地服务端

tk.Label(root, text="端口号：").grid(row=1, column=0, padx=10, pady=10)
port_entry = tk.Entry(root)
port_entry.grid(row=1, column=1, padx=10, pady=10)
port_entry.insert(0, "12345")

# 连接/断开按钮
connect_button = tk.Button(root, text="连接服务器", command=connect_server)
connect_button.grid(row=2, column=0, padx=10, pady=10)

disconnect_button = tk.Button(root, text="断开连接", command=disconnect)
disconnect_button.grid(row=2, column=1, padx=10, pady=10)

# 消息显示区域
message_text = tk.Text(root, height=15, width=70)
message_text.grid(row=3, column=0, columnspan=2, padx=10, pady=10)

# 消息输入框
message_entry = tk.Entry(root, width=50)
message_entry.grid(row=4, column=0, padx=10, pady=10)

# 发送按钮
send_button = tk.Button(root, text="发送消息", command=send_message)
send_button.grid(row=4, column=1, padx=10, pady=10)

# 状态标签
status_label = tk.Label(root, text="未连接", fg="red")
status_label.grid(row=5, column=0, columnspan=2, padx=10, pady=20)

# 运行主循环
root.mainloop()